using System.Collections.Generic;
using UnityEngine;

public class Drone : MonoBehaviour
{
	public Animator animator;

	public AudioSource engineAudioSource;

	public AudioClip outAudio;

	public AudioClip inAudio;

	public Weapon weapon;

	public float fireInterval = 1f;

	public float reloadTime = 5f;

	private bool isLeave;

	private bool isLeaveFired;

	[SerializeField]
	private List<Zombie> targets = new List<Zombie>();

	public bool canAttack;

	private void Start()
	{
		canAttack = true;
		InvokeRepeating("CheckFire", fireInterval, fireInterval);
	}

	private void Update()
	{
		if (weapon.ammo <= 0 && !isLeaveFired)
		{
			isLeaveFired = true;
			Invoke("Leave", fireInterval);
		}
		Vector2 vector = new Vector2(Player.Instance.transform.position.x - 1f, Player.Instance.transform.position.y + 0.3f);
		if (isLeave)
		{
			vector -= Vector2.right * 6f;
			vector += Vector2.up * 2f;
		}
		base.transform.position = Vector3.Lerp(base.transform.position, vector, 2f * Time.deltaTime);
		float value = vector.x - base.transform.position.x;
		animator.SetFloat("Blend", value);
		Aiming();
	}

	public void CheckFire()
	{
		if (canAttack && !isLeave && !isLeaveFired && targets.Count > 0)
		{
			animator.SetTrigger("Fire");
			weapon.Fire();
		}
	}

	public void Leave()
	{
		isLeave = true;
		Invoke("Enter", reloadTime + Mathf.Max(0f, Player.Instance.transform.position.x / 10f));
		engineAudioSource.PlayOneShot(outAudio);
	}

	public void Enter()
	{
		weapon.ammo = weapon.capacity;
		isLeave = false;
		isLeaveFired = false;
		engineAudioSource.PlayOneShot(inAudio);
	}

	public void Aiming()
	{
		if (targets.Count != 0)
		{
			if (!targets[0] || !targets[0].body)
			{
				targets.RemoveAt(0);
				return;
			}
			Vector3 position = weapon.transform.position;
			position.z = 0f;
			Vector3 position2 = targets[0].body.chest.transform.position;
			position.x = position2.x - position.x;
			position.y = position2.y - position.y;
			float z = Mathf.Atan2(position.y, position.x) * 57.29578f;
			weapon.transform.rotation = Quaternion.Euler(new Vector3(0f, 0f, z));
		}
	}

	private void OnTriggerEnter2D(Collider2D collision)
	{
		if (collision.tag == "Zombie" && collision.gameObject.TryGetComponent<Zombie>(out var component) && (bool)component.body)
		{
			targets.Add(component);
		}
	}

	private void OnTriggerExit2D(Collider2D collision)
	{
		if (collision.tag == "Zombie" && collision.gameObject.TryGetComponent<Zombie>(out var component) && (bool)component.body)
		{
			targets.Add(component);
		}
	}
}
